<template>
  <div class="box">
    <div class="searcharea">
      <!-- 搜索 -->
      <el-row>
        <el-col :span="24">
          <div class="query">
            <el-form :inline="true" :model="queryCraftBillParam" class="demo-form-inline">
              <el-form-item label="工艺路线名称">
                <el-input
                  v-model="queryCraftBillParam.CraftBillName"
                  placeholder="请输入"
                  clearable
                  style="width: 200px"
                />
              </el-form-item>

              <el-form-item>
                <el-button type="primary" :icon="Search" @click="SearchCraftBill()">搜索</el-button>
              </el-form-item>
            </el-form>
          </div>
        </el-col>
      </el-row>
    </div>

    <div class="contentarea">
      <!-- 功能按钮 -->
      <el-row>
        <el-col :span="24">
          <div class="functionbutton">
            <el-button type="primary" plain @click="addCraftBill()">添加</el-button>
            <el-button type="danger" plain @click="batchDeletionCraftBill()">批量删除</el-button>
          </div>
        </el-col>
      </el-row>

      <!-- 数据表格 -->
      <el-row>
        <el-col :span="24">
          <div>
            <el-table
              v-loading="tableloading"
              :data="tableData"
              border
              style="width: 100%"
              max-height="400px"
              :selection="selectedRows"
              @selection-change="handleSelectionChange"
              @row-click="getRowkey"
              show-overflow-tooltip
              empty-text="暂无数据"
            >
              <el-table-column type="selection" width="55" />
              <el-table-column type="index" label="序号" />
              <el-table-column prop="craftBillNo" label="工艺路线编码" width="180" />
              <el-table-column prop="craftBillName" label="工艺路线名称" />
              <el-table-column prop="remark" label="备注" />
              <el-table-column prop="creator" label="创建人" />
              <el-table-column prop="updator" label="修改人" />
              <el-table-column prop="createtime" label="创建时间" width="180" :formatter="formatColumnTime" />
              <el-table-column prop="updateDate" label="更新时间" width="180" :formatter="formatColumnTime" />
              <el-table-column fixed="right" label="操作" width="230">
                <template #default="scope">
                  <el-button type="danger" plain size="small" @click="DeleteCraftBillSingle(scope.row.id)">
                    删除
                  </el-button>

                  <el-button type="primary" plain size="small" @click="UpdateCraftBill(scope.row)">更新</el-button>
                  <el-button type="success" plain size="small" @click="GetCraftBillDetials(scope.row.id)"
                    >工序明细</el-button
                  >
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-col>

        <el-dialog v-model="UpdateDialogVisible" title="修改工艺路线" width="30%" align-center>
          <el-form
            ref="UpdateCraftBillFormRef"
            :model="UpdateCraftBillForm"
            :rules="CreateProcessRouteCraftBillRules"
            label-width="auto"
            style="padding: 20px"
          >
            <el-form-item label="编号">
              <el-input v-model="UpdateCraftBillForm.CraftBillNo" disabled placeholder="不输入则自动生成"> </el-input>
            </el-form-item>
            <el-form-item prop="CraftBillName" label="名称">
              <el-input v-model="UpdateCraftBillForm.CraftBillName" placeholder="请输入工艺路线名称"> </el-input>
            </el-form-item>
            <el-form-item label="说明" prop="CraftBillSort">
              <el-input v-model="UpdateCraftBillForm.CraftBillSort" placeholder="请输入" style="width: 260px">
              </el-input>
            </el-form-item>
            <el-form-item label="备注" prop="Remark">
              <el-input
                v-model="UpdateCraftBillForm.Remark"
                type="textarea"
                style="width: 260px"
                placeholder="请输入"
              />
            </el-form-item>
          </el-form>

          <template #footer>
            <div class="dialog-footer">
              <el-button @click="UpdateDialogVisible = false">取消</el-button>
              <el-button type="primary" @click="UpdateCraftBillDialog(UpdateCraftBillFormRef)">确认</el-button>
            </div>
          </template>
        </el-dialog>
      </el-row>

      <!-- 分页 -->
      <el-row>
        <el-col :span="24">
          <div class="demo-pagination-block" style="display: flex; justify-content: flex-end">
            <el-config-provider :locale="zhCn">
              <el-pagination
                v-model:current-page="queryCraftBillParam.PageIndex"
                v-model:page-size="queryCraftBillParam.PageSize"
                :page-sizes="[100, 200, 300, 400]"
                :small="false"
                :disabled="false"
                :background="true"
                layout="total, sizes, prev, pager, next, jumper"
                :total="queryCraftBillParam.totalCount"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
              >
              </el-pagination>
            </el-config-provider>
          </div>
        </el-col>
      </el-row>
    </div>

    <!-- 添加 -->
    <div>
      <!-- 添加工艺路线 -->
      <el-dialog
        v-model="centerDialogVisible"
        width="65%"
        title="添加工艺路线"
        append-to-body
        :before-close="CreateCraftBillhandleClose"
      >
        <el-row>
          <el-col :span="24">
            <el-form
              :inline="true"
              ref="CreateProcessRouteCraftBillFormRef"
              :model="CreateProcessRouteCraftBillForm"
              label-width="auto"
              class="demo-form-inline"
              :rules="CreateProcessRouteCraftBillRules"
            >
              <el-form-item label="路线编号" prop="CraftBillNo">
                <el-input
                  v-model="CreateProcessRouteCraftBillForm.CraftBillNo"
                  placeholder="不输入则自动生成"
                  style="width: 260px"
                >
                </el-input>
              </el-form-item>
              <el-form-item prop="CraftBillName" label="路线名称">
                <el-input
                  v-model="CreateProcessRouteCraftBillForm.CraftBillName"
                  placeholder="请输入工艺路线名称"
                  style="width: 260px"
                >
                </el-input>
              </el-form-item>
              <el-form-item label="说明" prop="CraftBillSort">
                <el-input
                  v-model="CreateProcessRouteCraftBillForm.CraftBillSort"
                  placeholder="请输入"
                  style="width: 260px"
                >
                </el-input>
              </el-form-item>

              <el-form-item label="备注" prop="Remark">
                <el-input
                  v-model="CreateProcessRouteCraftBillForm.Remark"
                  type="textarea"
                  style="width: 260px"
                  placeholder="请输入"
                />
              </el-form-item>
            </el-form>
          </el-col>
        </el-row>
        <el-divider content-position="left" style="margin: 15px 0">工序列表（长按拖动排序）</el-divider>

        <!-- 添加班组明细按钮 -->
        <el-row>
          <el-col :span="24">
            <div style="margin: 15px">
              <el-button type="primary" plain @click="addBillDetia()">添加工序</el-button>
              <el-button type="danger" plain @click="deleteBillDetia()">清空列表</el-button>
            </div>
          </el-col>
        </el-row>
        <!-- 工序明细数据表格 -->
        <el-row>
          <el-col :span="24">
            <el-table
              v-loading="tableloading"
              :data="ProcessRouteCraftBillDetial"
              height="300px"
              border
              style="width: 100%"
              max-height="300px"
              :selection="ProcessRouteCraftBillDetialSelectedRows"
              @selection-change="ProcessRouteCraftBillDetialSelectionChange"
              @row-click="getRowkey"
              show-overflow-tooltip
              empty-text="暂无数据"
              ref="tableNode"
              highlight-current-row
              row-key="id"
              :default-sort="{ prop: 'sort', order: 'ascending' }"
            >
              <!-- <el-table-column type="selection" width="55" /> -->
              <el-table-column label="排序">
                <template #default="scope">
                  <span>第 {{ scope.row.sort }} 道工序</span>
                </template>
              </el-table-column>

              <el-table-column prop="processNo" label="工序编号" />
              <el-table-column prop="processName" label="工序名称" />

              <el-table-column fixed="right" label="操作" align="center">
                <template #default="scope">
                  <el-button type="danger" plain size="small" @click="DeleteCraftBillDetiaSingle(scope.row.id)">
                    移除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-col>
        </el-row>

        <template #footer>
          <div class="dialog-footer">
            <el-button @click="CreateCraftBillhandleClose">取消</el-button>
            <el-button type="primary" @click="CreateCraftBillDialog(CreateProcessRouteCraftBillFormRef)"
              >确认</el-button
            >
          </div>
        </template>
      </el-dialog>

      <!-- 选择工序信息 -->
      <ChildComponent
        :querycolumns="querycolumns"
        :columns="columns"
        :data="SelectProcesstableData"
        :dialogVisible="SelectProcessDialogVisible"
        @selected="handleSelectedProcessData"
        @closed="handleDialogClosedProcess"
        @QueryForm="QueryProcessForms"
      />
    </div>

    <!--查看明细 -->
    <div>
      <el-drawer
        v-model="GetCraftBillDetialsDrawer"
        title="工艺路线明细"
        direction="rtl"
        :before-close="GetCraftBillDetialsDrawerClose"
        size="90%"
      >
        <div>
          <el-form :inline="true" :model="queryCraftBillDetialsParam" class="demo-form-inline">
            <el-form-item label="工序名称">
              <el-input
                v-model="queryCraftBillDetialsParam.CraftBillName"
                placeholder="请输入"
                clearable
                style="width: 200px"
              />
            </el-form-item>

            <el-form-item>
              <el-button type="primary" :icon="Search" @click="SearchCraftBillDetials()">搜索</el-button>
            </el-form-item>
          </el-form>
        </div>
        <el-divider content-position="left">工序列表（长按拖动排序）</el-divider>

        <el-table
          :data="GetCraftBillDetialsDrawerData"
          border
          style="width: 100%"
          show-overflow-tooltip
          empty-text="暂无数据"
          ref="GetCraftBillDetialsDrawerRef"
          highlight-current-row
          row-key="id"
        >
          <el-table-column label="排序">
            <template #default="scope">
              <span>第 {{ scope.row.processSort }} 道工序</span>
            </template>
          </el-table-column>

          <el-table-column prop="process.processNo" label="工序编号" />
          <el-table-column prop="process.processName" label="工序名称" />

          <el-table-column fixed="right" label="操作" align="center">
            <template #default="scope">
              <el-button type="danger" plain size="small" @click="DeleteCraftBillDetialsDrawerSingle(scope.row.id)">
                移除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-drawer>
    </div>
  </div>
</template>


<script setup lang="ts">
import { ApiGetProcessRoute_ProcessPageListAsync } from '../../api/processRoute/ProcessRouteProcessApi'
import ChildComponent from '@/components/CustomSelectDataDialog.vue'
import Sortable from 'sortablejs'
import { ref, Ref, reactive, onMounted, nextTick, watch } from 'vue'
import { Search } from '@element-plus/icons-vue'
import zhCn from 'element-plus/es/locale/lang/zh-cn'
import { ElMessageBox, ElNotification, FormInstance } from 'element-plus'
import {
  ApiGetProcessRoute_CraftBillPageListAsync,
  ApiGetProcessRoute_CraftBillDetialsPageListAsync,
  ApiDeletionProcessRoute_CraftBillDetialAsync,
  ApiUpdateProcessRoute_CraftBillDetialAsync,
  ApiDeletionProcessRoute_CraftBillAsync,
  ApiCreateProcessRoute_CraftBillAsync,
  ApiUpdateProcessRoute_CraftBillAsync
} from '../../api/processRoute/ProcessRouteCraftBillApi'
import { formatTime, capitalizeFirstLetter } from '../../utils/index'

const GetCraftBillDetialsDrawer = ref(false)

const GetCraftBillDetialsDrawerData = ref([])

// 存储选中的行数据
const CraftBillDetialsDrawerselectedRows = ref<string[]>([])

//明细查询参
const queryCraftBillDetialsParam: CraftBillParam = reactive({
  CraftBillName: null,
  PageIndex: 1,
  PageSize: 100,
  totalCount: 11
})

// 查看明细初始化拖拽排序
const CraftBillDetiainitSortable = () => {
  nextTick(() => {
    const el = GetCraftBillDetialsDrawerRef.value?.$el.querySelector('.el-table__body-wrapper table tbody')
    if (el) {
      sortableInstance = Sortable.create(el, {
        animation: 300,
        onEnd: (e: any) => {
          const oldIndex = e.oldIndex
          const newIndex = e.newIndex
          const movedItem = GetCraftBillDetialsDrawerData.value.splice(oldIndex, 1)[0]
          GetCraftBillDetialsDrawerData.value.splice(newIndex, 0, movedItem)
          // 更新sort值
          GetCraftBillDetialsDrawerData.value.forEach((item, index) => {
            item.processSort = index + 1
          })

          ApiUpdateProcessRoute_CraftBillDetialAsync(GetCraftBillDetialsDrawerData.value).then((res) => {
            ElNotification({
              message: '更新成功',
              offset: 100,
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    } else {
      console.error('无法找到表格元素')
    }
  })
}

//删除明细
const DeleteCraftBillDetialsDrawerSingle = (id: string) => {
  CraftBillDetialsDrawerselectedRows.value = [id]
  ApiDeletionProcessRoute_CraftBillDetialAsync(CraftBillDetialsDrawerselectedRows.value).then((res) => {
    ElNotification({
      message: '删除成功',
      offset: 100,
      type: 'success',
      duration: 2000
    })
    SearchCraftBillDetials()
    CraftBillDetialsDrawerselectedRows.value = []
  })
}

//明细打开对话框关闭时
const GetCraftBillDetialsDrawerClose = () => {
  queryCraftBillDetialsParam.CraftBillName = null
  GetCraftBillDetialsDrawer.value = false
}

//查询明细
const SearchCraftBillDetials = () => {
  ApiGetProcessRoute_CraftBillDetialsPageListAsync(queryCraftBillDetialsParam).then((res) => {
    GetCraftBillDetialsDrawerData.value = res.data.data
  })
}

// 查看明细打开对话框
const GetCraftBillDetials = (rowid: string) => {
  GetCraftBillDetialsDrawer.value = true
  queryCraftBillDetialsParam.CraftBillId = rowid
  SearchCraftBillDetials()
}

// 表格的引用
const tableNode = ref<FormInstance>()
const GetCraftBillDetialsDrawerRef = ref<FormInstance>()

let sortableInstance: Sortable | null = null

interface Process {
  ProcessName: string | null
  id: string | null
  PageIndex: number
  PageSize: number
  totalCount: number
  sort: number
}

const queryProcessParam: Process = reactive({
  ProcessName: null,
  id: null,
  PageIndex: 1,
  PageSize: 100,
  totalCount: 11,
  sort: 0
})

const SelectProcessDialogVisible = ref(false)
//选择工序表格数据
const SelectProcesstableData = ref([])

//工序明细
const ProcessRouteCraftBillDetial = ref<Process[]>([])

// 选择工序查询列
const querycolumns = [{ prop: 'processName', label: '工序名称' }]
// 选择工序列
const columns = [
  { prop: 'processNo', label: '工序编号' },
  { prop: 'processName', label: '工序名称' },
  { prop: 'creator', label: '创建人' },
  { prop: 'createtime', label: '创建时间' }
]

// 定义接口和类型
interface CraftBillParam {
  CraftBillName: string | null
  PageIndex: number
  PageSize: number
  totalCount: number
}

interface CraftBill {
  id: string
  ProcessRouteCraftBillDetials: any
}

// 响应式变量
const tableloading = ref(false)
const UpdateDialogVisible = ref(false)
const centerDialogVisible = ref(false)
const selectedRows = ref<string[]>([]) // 存储选中的行数据
const CreateProcessRouteCraftBillFormRef = ref<FormInstance>()

// 表单数据和验证规则
const CreateProcessRouteCraftBillForm: CraftBill = reactive({ id: '', ProcessRouteCraftBillDetials: [] })
const UpdateCraftBillForm: CraftBill = reactive({ id: '', ProcessRouteCraftBillDetials: [] })
const CreateProcessRouteCraftBillRules = reactive({
  CraftBillName: [{ required: true, message: '工艺路线名称不能为空', trigger: 'blur' }]
})

// 查询参数
const queryCraftBillParam: CraftBillParam = reactive({
  CraftBillName: null,
  PageIndex: 1,
  PageSize: 100,
  totalCount: 11
})

// 表格数据
const tableData = ref([])

//选择工序对话框查询操作
const QueryProcessForms = (form: Process) => {
  ApiGetProcessRoute_ProcessPageListAsync(form).then((res) => {
    SelectProcesstableData.value = res.data.data
  })
}

//添加班组人员明细
const addBillDetia = () => {
  SelectProcessDialogVisible.value = true

  //获取工序列表
  ApiGetProcessRoute_ProcessPageListAsync(queryProcessParam).then((res) => {
    SelectProcesstableData.value = res.data.data
  })
}

// 对话框关闭后执行的逻辑
const handleDialogClosedProcess = () => {
  SelectProcessDialogVisible.value = false
}

//选择工序对话框确定操作
const handleSelectedProcessData = (selectedData: Process[]) => {
  let duplicateCount = 0
  let addedCount = 0

  selectedData.forEach((item) => {
    if (ProcessRouteCraftBillDetial.value && Array.isArray(ProcessRouteCraftBillDetial.value)) {
      if (!ProcessRouteCraftBillDetial.value.some((data) => data.id === item.id)) {
        item.sort = ProcessRouteCraftBillDetial.value.length + 1
        ProcessRouteCraftBillDetial.value.push(item)
        addedCount++
      } else if (Array.isArray(ProcessRouteCraftBillDetial.value)) {
        duplicateCount++
      }
    } else {
      // 处理ProcessRouteCraftBillDetial.value为null或者非数组的情况
      ProcessRouteCraftBillDetial.value = selectedData
      addedCount = selectedData.length
    }
  })

  if (duplicateCount > 0) {
    ElNotification({
      message: `存在重复 ${duplicateCount} 条，已成功添加 ${addedCount} 条数据`,
      offset: 100,
      type: 'warning',
      duration: 3500
    })
  } else {
    ElNotification({
      message: `成功添加 ${addedCount} 条数据`,
      offset: 100,
      type: 'success',
      duration: 2000
    })
  }
}

//清空明细
const deleteBillDetia = () => {
  ProcessRouteCraftBillDetial.value = []
}

//添加明细移除
const DeleteCraftBillDetiaSingle = (rowId: string) => {
  const rowidindex = ProcessRouteCraftBillDetial.value.findIndex((g) => g.id === rowId)
  if (rowidindex != -1) {
    ProcessRouteCraftBillDetial.value.splice(rowidindex, 1)
    // 更新sort值
    ProcessRouteCraftBillDetial.value.forEach((item, index) => {
      item.sort = index + 1
    })
  }
}

// 初始化拖拽排序
const initSortable = () => {
  nextTick(() => {
    const el = tableNode.value?.$el.querySelector('.el-table__body-wrapper table tbody')
    if (el) {
      sortableInstance = Sortable.create(el, {
        animation: 300,
        onEnd: (e: any) => {
          const oldIndex = e.oldIndex
          const newIndex = e.newIndex
          const movedItem = ProcessRouteCraftBillDetial.value.splice(oldIndex, 1)[0]
          ProcessRouteCraftBillDetial.value.splice(newIndex, 0, movedItem)
          // 更新sort值
          ProcessRouteCraftBillDetial.value.forEach((item, index) => {
            item.sort = index + 1
          })
        }
      })
    } else {
      console.error('无法找到表格元素')
    }
  })
}

// 搜索工艺路线
const SearchCraftBill = () => {
  tableloading.value = true
  ApiGetProcessRoute_CraftBillPageListAsync(queryCraftBillParam)
    .then((res) => {
      tableData.value = res.data.data
      queryCraftBillParam.PageIndex = res.data.pageIndex
      queryCraftBillParam.PageSize = res.data.pageSize
      queryCraftBillParam.totalCount = res.data.totalCount
    })
    .finally(() => {
      tableloading.value = false
    })
}

// 关闭创建工艺路线对话框
const CreateCraftBillhandleClose = () => {
  const formEl = CreateProcessRouteCraftBillFormRef.value
  if (!formEl) return
  formEl.resetFields()
  centerDialogVisible.value = false
  ProcessRouteCraftBillDetial.value = []
}

// 打开添加工艺路线对话框
const addCraftBill = () => {
  centerDialogVisible.value = true
  ProcessRouteCraftBillDetial.value = []
}

// 监听对话框的显示状态，当对话框打开时初始化拖拽排序
watch([centerDialogVisible, GetCraftBillDetialsDrawer], ([centerVisible, drawerVisible]: [boolean, boolean]) => {
  if (centerVisible) {
    initSortable()
  } else if (drawerVisible) {
    CraftBillDetiainitSortable()
  } else if (sortableInstance) {
    sortableInstance.destroy()
    sortableInstance = null
  }

  if (drawerVisible) {
    // 处理GetCraftBillDetialsDrawer显示时的逻辑
  }
})

// 确认添加工艺路线
const CreateCraftBillDialog = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid) => {
    if (valid) {
      //判断是否添加了工序
      if (ProcessRouteCraftBillDetial.value.length < 1) {
        ElNotification({
          message: '请先添加工序',
          offset: 100,
          type: 'warning',
          duration: 2000
        })
        return
      }
      const Processdata = ProcessRouteCraftBillDetial.value.map((item) => ({
        ProcessId: item.id,
        ProcessSort: item.sort
      }))
      CreateProcessRouteCraftBillForm.ProcessRouteCraftBillDetials = Processdata
      ApiCreateProcessRoute_CraftBillAsync(CreateProcessRouteCraftBillForm).then((res) => {
        if (res.data.data) {
          ElNotification({
            message: '创建成功',
            offset: 100,
            type: 'success',
            duration: 2000
          })
          CreateCraftBillhandleClose()
          SearchCraftBill()
        }
      })
    }
  })
}

// 打开更新工艺路线信息对话框
const UpdateCraftBill = (row: { [key: string]: string | number }) => {
  Object.assign(UpdateCraftBillForm, capitalizeFirstLetter(row))
  UpdateDialogVisible.value = true
}

// 确认更新工艺路线信息
const UpdateCraftBillFormRef = ref<FormInstance>()
const UpdateCraftBillDialog = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid) => {
    if (valid) {
      ApiUpdateProcessRoute_CraftBillAsync(UpdateCraftBillForm).then((res) => {
        if (res.data.data) {
          ElNotification({
            message: '更新成功',
            offset: 100,
            type: 'success',
            duration: 2000
          })
          UpdateDialogVisible.value = false
          SearchCraftBill()
        }
      })
    }
  })
}

// 删除单个工艺路线
const DeleteCraftBillSingle = (id: string) => {
  selectedRows.value = [id]
  batchDeletionCraftBill()
}

// 批量删除工艺路线
const batchDeletionCraftBill = () => {
  if (selectedRows.value.length < 1) {
    ElNotification({
      message: '请先选择一条或更多信息',
      type: 'warning',
      offset: 100,
      duration: 2000
    })
    return
  }
  ElMessageBox.confirm('确实要删除这些信息吗?', '删除', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(() => {
      ApiDeletionProcessRoute_CraftBillAsync(selectedRows.value)
        .then((res) => {
          if (res.data.data) {
            ElNotification({
              message: '删除成功',
              offset: 100,
              type: 'success',
              duration: 2000
            })
            selectedRows.value = []
            SearchCraftBill()
          }
        })
        .catch(() => {
          selectedRows.value = []
        })
    })
    .catch(() => {
      selectedRows.value = []
    })
}

// 获取工序选择项
const handleSelectionChange = (val: CraftBill[]) => {
  selectedRows.value = val.map((item) => item.id)
}

// 时间转换
const formatColumnTime = (row: object, column: string, time: string | number | Date) => {
  if (time === null) {
    return ''
  }

  if (typeof time === 'string' || typeof time === 'number') {
    return formatTime(time)
  } else {
    return formatTime(time.getTime())
  }
}

// 每页条数
const handleSizeChange = (e: number) => {
  queryCraftBillParam.PageSize = e
  SearchCraftBill()
}

// 当前页变化
const handleCurrentChange = (e: number) => {
  queryCraftBillParam.PageIndex = e
  SearchCraftBill()
}

// 初次加载数据
onMounted(() => {
  SearchCraftBill()
})
</script>



<style lang="less"  scoped>
@import '../../assets/globle/index.css';
</style>
